﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using E4RPTools;

namespace DBTractores
{
    public class PartMerger : IProgressWorker
    {
        #region Members

        private readonly Dictionary<string, Part> _parts;
        private readonly Result _errors;
        private readonly DataClassesDataContext _dataContext;
        private readonly List<Part> _existingParts;

        #endregion
        
        #region Events

        public event EventHandler DocumentProcessing;

        #endregion

        #region Properties

        public int DocumentCount { get; private set; }

        public int DocumentIndex { get; private set; }

        public string DocumentNumber { get; private set; }

        #endregion

        #region Public Methods

        public PartMerger(Result errors, Dictionary<string, Part> parts, DataClassesDataContext dataContext, List<Part> existingParts)
        {
            _parts = parts;
            _errors = errors;
            _dataContext = dataContext;
            _existingParts = existingParts;
        }

        public bool Work()
        {
            _errors.Reset();
            _existingParts.Clear();
            DocumentCount = _dataContext.Artigos.Count();
            return MergeParts();            
        }        

        #endregion

        #region Protected Methods

        virtual protected void OnDocumentProcessing()
        {
            var documentProcessing = DocumentProcessing;
            if (documentProcessing != null)
                documentProcessing(this, new EventArgs());
        }

        #endregion

        #region Private Methods

        private bool MergeParts()
        {            
            _dataContext.Refresh(RefreshMode.OverwriteCurrentValues, _dataContext.ArtigoMoedas);
            foreach (var product in _dataContext.Artigos)
            {
                if (_parts.ContainsKey(product.Artigo1))
                {
                    DocumentNumber = product.Artigo1;
                    DocumentIndex++;
                    var currency = _dataContext.ArtigoMoedas.Where(a => a.Artigo == product.Artigo1);
                    var part = _parts[product.Artigo1];
                    part.CurrentPrice = currency.First().PVP1.Value;
                    part.Selected = true;
                    _existingParts.Add(part);
                }
                OnDocumentProcessing();
            }
            return true;
        }

        #endregion
    }
}
